package com.ficv.findme;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import android.content.ContentResolver;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.util.Log;

public class SendPosition extends AsyncTask<String, Void, String> {

    private Throwable exception;

    private ContentResolver contentResolver;
    private Context ctx;
    
    
    public ContentResolver getContentResolver() {
		return contentResolver;
	}



	public void setContentResolver(ContentResolver contentResolver) {
		this.contentResolver = contentResolver;
	}



	public SendPosition(ContentResolver contentResolver, Context ctx) {
		super();
		this.contentResolver = contentResolver;
		this.ctx=ctx;
	}



	protected String doInBackground(String... data)  {

				try 
				{
					String result=null;
				  	String total = IOUtils.toString(new FileReader("/mnt/sdcard/findmedat.dat"));
				  	Log.v("GetNotification","deviceId: " + total);
				  	String androidId=total.split(":")[0];
				  	
				  	
					//String androidId=Secure.getString(getContentResolver(), Secure.ANDROID_ID);	
					//String androidId="69d6d4731c4b6725";
					//String url = getUrl(androidId, data);
					
				  	if(androidId!=null  && !androidId.equalsIgnoreCase("")) {
				  	
					  	String url = MainActivity.URL_BASE + "geoLocate";
						Log.v("SendPosition","Position: " + url);
						
						HttpHeaders requestHeaders = new HttpHeaders();
						List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
						acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
						requestHeaders.setAccept(acceptableMediaTypes);
						
						// Populate the headers in an HttpEntity object to use for the request
						//HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
						HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(getFormData(androidId, data), requestHeaders);
	
						// Create a new RestTemplate instance
						RestTemplate restTemplate = new RestTemplate();
						
						// Perform the HTTP GET request
						ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
						
						// Return the list of states
						result  = responseEntity.getBody();
						Log.v("SendPosition","result: " + result);
				  	}
				  	
					return result;

				} 
				catch(Throwable e) 
				{
					this.exception = e;
					Log.e("TAG", e.getMessage(), e);
					return null;
				} 

			}



	public String getUrl(String androidId, String... data) throws Throwable{
 
		
	     String codigoPostal=null;

	     String poblacion=null;

	     String provincia=null;

	     String calle=null;

	     String barrio=null;

	     String distrito=null;
	    
	     String region=null;

	     String pais=null; 
	     
		Geocoder myLocation = new Geocoder(ctx, Locale.getDefault());   
		List<Address> myList = myLocation.getFromLocation(Double.parseDouble(data[0]),Double.parseDouble(data[1]), 10);
		
		
		for(Address a: myList) {
			//Log.i(GpsService.MiService, "address: " + a);
			if(calle==null  && a.getAddressLine(0)!=null) calle=a.getAddressLine(0);
			else if(codigoPostal==null  && a.getPostalCode()!=null) codigoPostal=a.getPostalCode();
			else if(barrio==null  && a.getSubLocality()!=null) barrio=a.getSubLocality();
			else if(distrito==null  && a.getSubLocality()!=null) distrito=a.getSubLocality();
			else if(poblacion==null  && a.getLocality()!=null) poblacion=a.getLocality();			
			else if(provincia==null  && a.getSubAdminArea()!=null) provincia=a.getSubAdminArea();			
			else if(region==null  &&  a.getAdminArea()!=null) region=a.getAdminArea();
			else if(pais==null  && a.getCountryCode()!=null) pais=a.getCountryCode();			
		}
		
		String url = MainActivity.URL_BASE + "position?id=" + androidId + "&lat="+ data[0] + "&lon="+ data[1] + "&precision="+ data[2] + 
				"&codigoPostal=" + codigoPostal + 
				"&poblacion=" + poblacion +
				"&calle=" + calle +										
				"&barrio=" + barrio +
				"&distrito=" + distrito +
				"&region=" + region +
				"&pais=" + pais +  				
				"&time=" + (new Date()).getTime();
		return url;
	}   
		 
	public  MultiValueMap<String, Object> getFormData(String androidId, String... data) throws Throwable{
	
		 MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();

		
	     String codigoPostal=null;

	     String poblacion=null;

	     String provincia=null;

	     String calle=null;

	     String barrio=null;

	     String distrito=null;
	    
	     String region=null;

	     String pais=null; 
	     
		Geocoder myLocation = new Geocoder(ctx, Locale.getDefault());   
		List<Address> myList = myLocation.getFromLocation(Double.parseDouble(data[0]),Double.parseDouble(data[1]), 10);
		
		
		for(Address a: myList) {
			//Log.i(GpsService.MiService, "address: " + a);
			if(calle==null  && a.getAddressLine(0)!=null) calle=a.getAddressLine(0);
			else if(codigoPostal==null  && a.getPostalCode()!=null) codigoPostal=a.getPostalCode();
			else if(barrio==null  && a.getSubLocality()!=null) barrio=a.getSubLocality();
			else if(distrito==null  && a.getSubLocality()!=null) distrito=a.getSubLocality();
			else if(poblacion==null  && a.getLocality()!=null) poblacion=a.getLocality();			
			else if(provincia==null  && a.getSubAdminArea()!=null) provincia=a.getSubAdminArea();			
			else if(region==null  &&  a.getAdminArea()!=null) region=a.getAdminArea();
			else if(pais==null  && a.getCountryCode()!=null) pais=a.getCountryCode();			
		}
		
		if(calle==null)  calle="No disponible";
		 if(codigoPostal==null) codigoPostal="No disponible";
		 if(barrio==null) barrio="No disponible";
		 if(distrito==null ) distrito="No disponible";
		 if(poblacion==null) poblacion="No disponible";
		 if(provincia==null ) provincia="No disponible";			
		if(region==null) region="No disponible";
		 if(pais==null) pais="No disponible";
		
		// populate the data to post


		formData.add("id", androidId);
		formData.add("lat", data[0]);
		formData.add("lon", data[1]);
		formData.add("precision", data[2]);
		formData.add("codigoPostal", codigoPostal);
		formData.add("poblacion", poblacion);
		formData.add("provincia", provincia);		
		formData.add("calle", calle);
		formData.add("barrio", barrio);
		formData.add("distrito", distrito);
		formData.add("region", region);
		formData.add("pais", pais);		
		formData.add("time", String.valueOf((new Date()).getTime()));		


		
		return formData;
	}   

 }